{% extends "base.html" %}

{% block title %}{{ comic.title }} - {{ chapter.title }} - 漫画阅读器{% endblock %}

{% block body_class %}reader-page{% endblock %}

{% block content %}
<div class="reader-container" id="reader-container">
    <!-- 阅读器顶部栏 -->
    <div class="reader-header" id="reader-header">
        <div class="header-left">
            <button class="back-btn" onclick="goBack()">
                <span class="btn-icon">←</span>
                <span class="btn-text">返回</span>
            </button>
        </div>
        
        <div class="header-center">
            <h1 class="comic-title">{{ comic.title }}</h1>
            <div class="chapter-info">
                <span class="chapter-title">{{ chapter.title }}</span>
                <span class="page-indicator">
                    <span class="current-page">{{ page_num }}</span>
                    <span class="separator">/</span>
                    <span class="total-pages">{{ total_pages }}</span>
                </span>
            </div>
        </div>
        
        <div class="header-right">
            <button class="menu-btn" onclick="toggleMenu()">
                <span class="btn-icon">☰</span>
            </button>
        </div>
    </div>

    <!-- 阅读器主体 -->
    <div class="reader-main" id="reader-main">
        <!-- 图片显示区域 -->
        <div class="image-container" id="image-container">
            <div class="image-wrapper" id="image-wrapper">
                <img id="current-image" 
                     src="/api/image/{{ current_page.image_path | urlencode }}" 
                     alt="第{{ page_num }}页"
                     class="comic-image"
                     onload="onImageLoad()"
                     onerror="onImageError()">
            </div>
            
            <!-- 加载指示器 -->
            <div class="image-loading" id="image-loading">
                <div class="loading-spinner">
                    <div class="spinner"></div>
                </div>
                <div class="loading-text">加载中...</div>
            </div>
            
            <!-- 错误提示 -->
            <div class="image-error" id="image-error" style="display: none;">
                <div class="error-icon">❌</div>
                <div class="error-text">图片加载失败</div>
                <button class="retry-btn" onclick="retryLoadImage()">重试</button>
            </div>
        </div>

        <!-- 导航按钮 -->
        <div class="nav-buttons">
            {% if has_prev_page %}
            <button class="nav-btn prev-btn" onclick="prevPage()" title="上一页">
                <span class="btn-icon">←</span>
            </button>
            {% endif %}
            
            {% if has_next_page %}
            <button class="nav-btn next-btn" onclick="nextPage()" title="下一页">
                <span class="btn-icon">→</span>
            </button>
            {% endif %}
        </div>
    </div>

    <!-- 阅读器底部栏 -->
    <div class="reader-footer" id="reader-footer">
        <div class="progress-container">
            <div class="progress-bar">
                <div class="progress-fill" style="width: {{ (page_num / total_pages * 100) | round(1) }}%"></div>
            </div>
            <div class="progress-text">{{ page_num }} / {{ total_pages }}</div>
        </div>
        
        <div class="footer-actions">
            {% if prev_chapter %}
            <button class="action-btn" onclick="goToChapter('{{ prev_chapter.id }}', 1)">
                <span class="btn-icon">⏮️</span>
                <span class="btn-text">上一章</span>
            </button>
            {% endif %}
            
            <button class="action-btn" onclick="toggleFullscreen()">
                <span class="btn-icon">⛶</span>
                <span class="btn-text">全屏</span>
            </button>
            
            {% if next_chapter %}
            <button class="action-btn" onclick="goToChapter('{{ next_chapter.id }}', 1)">
                <span class="btn-icon">⏭️</span>
                <span class="btn-text">下一章</span>
            </button>
            {% endif %}
        </div>
    </div>

    <!-- 侧边菜单 -->
    <div class="reader-menu" id="reader-menu">
        <div class="menu-overlay" onclick="toggleMenu()"></div>
        <div class="menu-content">
            <div class="menu-header">
                <h2 class="menu-title">{{ comic.title }}</h2>
                <button class="menu-close" onclick="toggleMenu()">×</button>
            </div>
            
            <div class="menu-body">
                <!-- 章节列表 -->
                <div class="menu-section">
                    <h3 class="section-title">章节列表</h3>
                    <div class="chapter-list">
                        {% for ch in comic.chapters %}
                        <div class="chapter-item {% if ch.id == chapter.id %}active{% endif %}">
                            <a href="{{ url_for('main.reader', comic_id=comic.id, chapter_id=ch.id, page_num=1) }}" 
                               class="chapter-link">
                                <span class="chapter-name">{{ ch.title }}</span>
                                <span class="chapter-pages">{{ ch.page_count }}页</span>
                            </a>
                        </div>
                        {% endfor %}
                    </div>
                </div>
                
                <!-- 页面跳转 -->
                <div class="menu-section">
                    <h3 class="section-title">页面跳转</h3>
                    <div class="page-jump">
                        <input type="number" 
                               id="page-input" 
                               min="1" 
                               max="{{ total_pages }}" 
                               value="{{ page_num }}" 
                               class="page-input">
                        <button onclick="jumpToPage()" class="jump-btn">跳转</button>
                    </div>
                </div>
                
                <!-- 阅读设置 -->
                <div class="menu-section">
                    <h3 class="section-title">阅读设置</h3>
                    <div class="setting-group">
                        <div class="setting-item">
                            <label class="setting-label">图片质量</label>
                            <select id="quality-select" class="setting-select" onchange="changeQuality()">
                                <option value="60">低质量</option>
                                <option value="85" selected>标准质量</option>
                                <option value="95">高质量</option>
                                <option value="100">原始质量</option>
                            </select>
                        </div>
                        
                        <div class="setting-item">
                            <label class="setting-label">自动隐藏控制栏</label>
                            <input type="checkbox" id="auto-hide" class="setting-checkbox" onchange="toggleAutoHide()" checked>
                        </div>
                        
                        <div class="setting-item">
                            <label class="setting-label">预加载页面</label>
                            <input type="checkbox" id="preload" class="setting-checkbox" onchange="togglePreload()" checked>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="{{ url_for('static', filename='js/gesture-handler.js') }}"></script>
<script src="{{ url_for('static', filename='js/image-cache.js') }}"></script>

<script>
// 阅读器状态
const readerState = {
    comicId: '{{ comic.id }}',
    chapterId: '{{ chapter.id }}',
    currentPage: {{ page_num }},
    totalPages: {{ total_pages }},
    isFullscreen: false,
    autoHide: true,
    preload: true,
    quality: 85,
    hideTimer: null,
    touchStartX: 0,
    touchStartY: 0,
    isLoading: false
};

// 初始化阅读器
document.addEventListener('DOMContentLoaded', function() {
    initReader();
    setupEventListeners();
    setupGestureHandlers();
    setupImageCache();
    
    // 预加载相邻页面
    if (readerState.preload) {
        preloadAdjacentPages();
    }
});

// 初始化阅读器
function initReader() {
    // 设置初始状态
    const container = document.getElementById('reader-container');
    container.classList.add('reader-active');
    
    // 自动隐藏控制栏
    if (readerState.autoHide) {
        startAutoHideTimer();
    }
    
    // 阻止默认滚动
    document.body.style.overflow = 'hidden';
}

// 设置事件监听器
function setupEventListeners() {
    // 键盘事件
    document.addEventListener('keydown', handleKeydown);
    
    // 鼠标移动事件
    document.addEventListener('mousemove', showControls);
    
    // 窗口大小变化
    window.addEventListener('resize', handleResize);
    
    // 全屏状态变化
    document.addEventListener('fullscreenchange', handleFullscreenChange);
}

// 设置手势处理
function setupGestureHandlers() {
    const imageContainer = document.getElementById('image-container');
    
    // 触摸事件
    imageContainer.addEventListener('touchstart', handleTouchStart, { passive: false });
    imageContainer.addEventListener('touchmove', handleTouchMove, { passive: false });
    imageContainer.addEventListener('touchend', handleTouchEnd, { passive: false });
    
    // 点击事件
    imageContainer.addEventListener('click', handleClick);
    
    // 双击事件
    let lastTap = 0;
    imageContainer.addEventListener('touchend', function(e) {
        const currentTime = new Date().getTime();
        const tapLength = currentTime - lastTap;
        if (tapLength < 500 && tapLength > 0) {
            handleDoubleClick(e);
        }
        lastTap = currentTime;
    });
}

// 触摸开始
function handleTouchStart(e) {
    e.preventDefault();
    const touch = e.touches[0];
    readerState.touchStartX = touch.clientX;
    readerState.touchStartY = touch.clientY;
}

// 触摸移动
function handleTouchMove(e) {
    e.preventDefault();
}

// 触摸结束
function handleTouchEnd(e) {
    e.preventDefault();
    
    if (!e.changedTouches || e.changedTouches.length === 0) return;
    
    const touch = e.changedTouches[0];
    const deltaX = touch.clientX - readerState.touchStartX;
    const deltaY = touch.clientY - readerState.touchStartY;
    
    // 检查是否为有效滑动
    const minSwipeDistance = 50;
    const maxVerticalDistance = 100;
    
    if (Math.abs(deltaX) > minSwipeDistance && Math.abs(deltaY) < maxVerticalDistance) {
        if (deltaX > 0) {
            // 右滑 - 上一页
            prevPage();
        } else {
            // 左滑 - 下一页
            nextPage();
        }
    }
}

// 点击事件
function handleClick(e) {
    const rect = e.target.getBoundingClientRect();
    const clickX = e.clientX - rect.left;
    const width = rect.width;
    
    if (clickX < width / 3) {
        // 左侧点击 - 上一页
        prevPage();
    } else if (clickX > (width * 2) / 3) {
        // 右侧点击 - 下一页
        nextPage();
    } else {
        // 中间点击 - 切换控制栏
        toggleControls();
    }
}

// 双击事件
function handleDoubleClick(e) {
    const img = document.getElementById('current-image');
    if (img.style.transform === 'scale(2)') {
        img.style.transform = 'scale(1)';
    } else {
        img.style.transform = 'scale(2)';
    }
}

// 键盘事件
function handleKeydown(e) {
    switch(e.key) {
        case 'ArrowLeft':
            e.preventDefault();
            prevPage();
            break;
        case 'ArrowRight':
            e.preventDefault();
            nextPage();
            break;
        case 'Escape':
            if (readerState.isFullscreen) {
                exitFullscreen();
            } else {
                goBack();
            }
            break;
        case 'f':
        case 'F':
            toggleFullscreen();
            break;
        case ' ':
            e.preventDefault();
            nextPage();
            break;
    }
}

// 上一页
function prevPage() {
    if (readerState.currentPage > 1) {
        navigateToPage(readerState.currentPage - 1);
    } else if ({{ 'true' if prev_chapter else 'false' }}) {
        // 跳转到上一章的最后一页
        goToChapter('{{ prev_chapter.id if prev_chapter else "" }}', -1);
    }
}

// 下一页
function nextPage() {
    if (readerState.currentPage < readerState.totalPages) {
        navigateToPage(readerState.currentPage + 1);
    } else if ({{ 'true' if next_chapter else 'false' }}) {
        // 跳转到下一章的第一页
        goToChapter('{{ next_chapter.id if next_chapter else "" }}', 1);
    }
}

// 导航到指定页面
function navigateToPage(pageNum) {
    if (readerState.isLoading) return;
    
    const url = `/reader/${readerState.comicId}/${readerState.chapterId}/${pageNum}`;
    window.location.href = url;
}

// 跳转到章节
function goToChapter(chapterId, pageNum) {
    if (!chapterId) return;
    
    showLoading('正在切换章节...');
    
    if (pageNum === -1) {
        // 获取章节最后一页
        fetch(`/api/chapters/${chapterId}/pages`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    const lastPage = data.data.pages.length;
                    const url = `/reader/${readerState.comicId}/${chapterId}/${lastPage}`;
                    window.location.href = url;
                } else {
                    throw new Error(data.message);
                }
            })
            .catch(error => {
                console.error('获取章节信息失败:', error);
                hideLoading();
            });
    } else {
        const url = `/reader/${readerState.comicId}/${chapterId}/${pageNum}`;
        window.location.href = url;
    }
}

// 跳转到指定页面
function jumpToPage() {
    const pageInput = document.getElementById('page-input');
    const pageNum = parseInt(pageInput.value);
    
    if (pageNum >= 1 && pageNum <= readerState.totalPages) {
        navigateToPage(pageNum);
    } else {
        alert(`请输入1到${readerState.totalPages}之间的页码`);
    }
}

// 图片加载完成
function onImageLoad() {
    hideLoading();
    document.getElementById('image-loading').style.display = 'none';
    document.getElementById('image-error').style.display = 'none';
    document.getElementById('current-image').style.display = 'block';
}

// 图片加载错误
function onImageError() {
    hideLoading();
    document.getElementById('image-loading').style.display = 'none';
    document.getElementById('image-error').style.display = 'flex';
    document.getElementById('current-image').style.display = 'none';
}

// 重试加载图片
function retryLoadImage() {
    const img = document.getElementById('current-image');
    document.getElementById('image-error').style.display = 'none';
    document.getElementById('image-loading').style.display = 'flex';
    img.src = img.src + '?' + new Date().getTime();
}

// 切换菜单
function toggleMenu() {
    const menu = document.getElementById('reader-menu');
    menu.classList.toggle('active');
}

// 切换全屏
function toggleFullscreen() {
    if (!document.fullscreenElement) {
        document.documentElement.requestFullscreen().then(() => {
            readerState.isFullscreen = true;
        });
    } else {
        document.exitFullscreen().then(() => {
            readerState.isFullscreen = false;
        });
    }
}

// 退出全屏
function exitFullscreen() {
    if (document.fullscreenElement) {
        document.exitFullscreen();
    }
}

// 全屏状态变化
function handleFullscreenChange() {
    readerState.isFullscreen = !!document.fullscreenElement;
    const container = document.getElementById('reader-container');
    
    if (readerState.isFullscreen) {
        container.classList.add('fullscreen');
    } else {
        container.classList.remove('fullscreen');
    }
}

// 显示控制栏
function showControls() {
    const header = document.getElementById('reader-header');
    const footer = document.getElementById('reader-footer');
    
    header.classList.add('visible');
    footer.classList.add('visible');
    
    if (readerState.autoHide) {
        startAutoHideTimer();
    }
}

// 切换控制栏
function toggleControls() {
    const header = document.getElementById('reader-header');
    const footer = document.getElementById('reader-footer');
    
    header.classList.toggle('visible');
    footer.classList.toggle('visible');
    
    if (header.classList.contains('visible') && readerState.autoHide) {
        startAutoHideTimer();
    }
}

// 开始自动隐藏计时器
function startAutoHideTimer() {
    clearTimeout(readerState.hideTimer);
    readerState.hideTimer = setTimeout(() => {
        const header = document.getElementById('reader-header');
        const footer = document.getElementById('reader-footer');
        header.classList.remove('visible');
        footer.classList.remove('visible');
    }, 3000);
}

// 切换自动隐藏
function toggleAutoHide() {
    const checkbox = document.getElementById('auto-hide');
    readerState.autoHide = checkbox.checked;
    
    if (!readerState.autoHide) {
        clearTimeout(readerState.hideTimer);
        showControls();
    }
}

// 切换预加载
function togglePreload() {
    const checkbox = document.getElementById('preload');
    readerState.preload = checkbox.checked;
}

// 改变图片质量
function changeQuality() {
    const select = document.getElementById('quality-select');
    readerState.quality = parseInt(select.value);
    
    // 重新加载当前图片
    const img = document.getElementById('current-image');
    const currentSrc = img.src.split('?')[0];
    img.src = `${currentSrc}?quality=${readerState.quality}&t=${Date.now()}`;
}

// 预加载相邻页面
function preloadAdjacentPages() {
    const preloadPages = 2;
    
    for (let i = 1; i <= preloadPages; i++) {
        // 预加载后面的页面
        if (readerState.currentPage + i <= readerState.totalPages) {
            preloadImage(`/api/image/{{ chapter.pages[page_num - 1].image_path | urlencode }}?quality=${readerState.quality}`);
        }
        
        // 预加载前面的页面
        if (readerState.currentPage - i >= 1) {
            preloadImage(`/api/image/{{ chapter.pages[page_num - 1].image_path | urlencode }}?quality=${readerState.quality}`);
        }
    }
}

// 预加载图片
function preloadImage(src) {
    const img = new Image();
    img.src = src;
}

// 返回
function goBack() {
    if (history.length > 1) {
        history.back();
    } else {
        window.location.href = `/comic/${readerState.comicId}`;
    }
}

// 窗口大小变化
function handleResize() {
    // 重新调整图片大小
    const img = document.getElementById('current-image');
    if (img) {
        img.style.transform = 'scale(1)';
    }
}

// 页面卸载时清理
window.addEventListener('beforeunload', function() {
    document.body.style.overflow = '';
    clearTimeout(readerState.hideTimer);
});
</script>
{% endblock %}